package com.spundhan.xtrac.db;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper {

	private static String DB_NAME = "EXPENSE";

	private SQLiteDatabase myDataBase;

	private final Context myContext;

	public DataBaseHelper(Context context) {

		super(context, Database.DATABASE_NAME, null, 1);
		this.myContext = context;
	}

	public void createDatabase() {

		this.getReadableDatabase();

		try {
			copyDataBase();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void copyDataBase() {

		String outFileName = Database.DATABASE_PATH + Database.DATABASE_NAME;

		InputStream myInput = null;
		OutputStream myOutput = null;

		try {
			myInput = myContext.getAssets().open(Database.DATABASE_NAME);
			myOutput = new FileOutputStream(outFileName);
			byte[] buffer = new byte[1024];
			int length;

			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}

			myOutput.flush();
			myOutput.close();
			myInput.close();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SQLiteDatabase openDataBase() {

		// Open the database
		String myPath = Database.DATABASE_PATH + DB_NAME;
		return myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READWRITE);

	}

	@Override
	public synchronized void close() {

		if (myDataBase != null)
			myDataBase.close();

		super.close();

	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}
}
